<?php


namespace app\user\controller;


use app\common\model\MiniApp as MiniAppModel;
use app\common\model\WechatShareLink as WechatShareLinkModel;
use app\user\logic\ShareLinkLogic;
use app\user\model\User as UserModel;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Messages\Article;
//use GuzzleHttp\Exception\GuzzleException;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Request;

class Test extends Controller
{


    public function getCoverMediaId()
    {
      $res=  ShareLinkLogic::getCoverMediaId();
      return $res;
    //   $this->result($res,200);
    }

    public function test22()
    {
        $url="http://m.v.qq.com/play/play.html?vid=f3133nw82lx&url_from=share&second_share=0&share_from=copy&pgid=page_smallvideo_immersive&ztid=120136&mo";


        $query = getUrlQuery( $url );
        $this->result($query,200);
        $vid = $query['vid'];
        $url = "http://vv.video.qq.com/getinfo?vids=".$vid."&platform=101001&charge=0&otype=json";
       $url2= $this->txSolve($url);
       $this->result($url,200);
    }

    //解析腾讯视频
    public function txSolve($url)
    {
        $tencentVideoInfo = $this->curl_request($url);
        $tencentVideoJson = substr(explode('QZOutputJson=',$tencentVideoInfo)[1],0,-1);
        $tencentVideoArray = json_decode($tencentVideoJson,true);
        $fvkey = $tencentVideoArray['vl']['vi'][0]['fvkey'];
        $fn = $tencentVideoArray['vl']['vi'][0]['fn'];
        $url = $tencentVideoArray['vl']['vi'][0]['ul']['ui'][0]['url'];
        $video_url = $url.$fn.'?vkey='.$fvkey;
        return $video_url;
    }

    function curl_request($url,$https=true,$method='get',$data=null){
        //1.初识化curl
        $ch = curl_init($url);
        //2.根据实际请求需求进行参数封装
        //返回数据不直接输出
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        //如果是https请求
        if($https === true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        }
        //如果是post请求
        if($method === 'post'){
            //开启发送post请求选项
            curl_setopt($ch,CURLOPT_POST,true);
            //发送post的数据
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        //3.发送请求
        $result = curl_exec($ch);
        //4.返回返回值，关闭连接
        curl_close($ch);
        return $result;
    }

    //添加虚假的收益数据
    public function   addFakeIncomeData(){

        $id=   23   ;   //id
        $count=   2  ;  //次数

        //
          for ($i=0;$i<$count;$i++){
             $res= Db::table('ad_play_history')->insert([
                  'promote_user_id'=>$id,
                  'tt_user_id'=>0,
                  'mini_app_code'=>'movie',
                  'product_id'=>0,
                  'url_id'=>0,
                  'ip'=>0,
                  'add_time'=>time()
              ]);
          }

          $this->result('',200,'成功');
    }


    //获取素材的短连接
    public function getLongUrl($long_url)
    {

        $curl = curl_init();
//        $long_url=   "http://mp.weixin.qq.com/s?__biz=MzI5MDQyMTEzMw==&mid=100000058&idx=1&sn=df035850513c96a8e8a92077a955b274&chksm=6c2161d85b56e8ceea93a7d32b18f83e00243b9ccc33e4f9f53eb08d4d435d607a763945ed0c#rd";

        $post_url= "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&".substr($long_url,26);

        curl_setopt_array($curl, array(
//            CURLOPT_URL => "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&__biz=MzI5MDQyMTEzMw==",
            CURLOPT_URL => $post_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "referer: ".$long_url,
                "Cookie: rewardsn=; wxtokenkey=777"
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $obj=json_decode($response);

        return $obj->appmsg_compact_url;
//        $this->result( $obj,200);
//        echo $response;
    }


    // 给指定用户发钱
    public  function pay_money($user_id=0,$money=0)
    {

            $config = Config::get("miniprogram.wechat_pay");

            $app = Factory::payment($config);
            $res=  $app->transfer->toBalance([
                'partner_trade_no' => time(), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                'openid' => 'osvPs4mzq31QuySsvddtwzAHjZpg',
                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                're_user_name' => '邹甜', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount' => 100, // 企业付款金额，单位为分
                'desc' => '推广佣金', // 企业付款操作说明信息。必填
            ]);

        $this->result($res,200);
    }


    public  function userList()
    {
        $app = Factory::officialAccount(ShareLinkLogic::getAccount());
        $list= $app->user->list();  // $nextOpenId 可选

        $list2=[];
//
        foreach ($list->data->openid as $item) {
            $user = $app->user->get($item);
            array_push($list2,$user);
        }

        $this->result($list2,200);
    }



    public function check()
    {
        $app = Factory::officialAccount(ShareLinkLogic::getAccount());
        $info=$app->broadcasting->status('2247483718');

        $this->result($info,200);

    }


    //发送图文消息推送
    public function send()
    {
        $app = Factory::officialAccount(ShareLinkLogic::getAccount());

//        //上传封面
        $result = $app->material->uploadImage(Env::get('Cong')."controller/cover.png");
//
        $thumb_media_id=$result->media_id;
        $mini_app = MiniAppModel::where('code', 'test')->find();
//        // 上传单篇图文
        $article = new Article([
            'title' => '没有推送了也可以22？',
            'thumb_media_id'=>$thumb_media_id,
            'show_cover' => 0, // 是否在文章内容显示封面图片
            "content_source_url" => 'http://www.baidu.com',
            "content"=>ShareLinkLogic::buildContent($mini_app,0,0),
        ]);

        $res2=$app->material->uploadArticle($article);

        //发推送
        $res= $app->broadcasting->sendNews($res2->media_id, ["ojdcfxEJqsqz_cO2Z7TBWKEK1Zto", "ojdcfxEJJMzOrC9U3auyhZ-qB1qc"]);



        try {
            $resource = $app->material->get($res2->media_id);
        } catch (InvalidConfigException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        } catch (GuzzleException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        }

        //存数据库
//        $res2=WechatShareLinkModel::create( $data);

        $data=[
//            'res2'=>$res2,
            'res'=>$res,
//            'info'=>$info,
//            'long_url'=>$long_url
        ];
        $this->result($res,200);
    }

    //支付功能
    public function pay()
    {
        $config =  Config::get("miniprogram.wechat_pay");

        $payment  = Factory::payment($config);
        $jssdk = $payment->jssdk;


        $result = $payment ->order->unify([
            'body' => '会员费用',
            'out_trade_no' => '201508061252346',
            'total_fee' => 1,
//            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',        // 请对应换成你的支付方式对应的值类型
            'openid' => 'osvPs4s6niApeoNZwxj2n6lPpjx0',
        ]);

        $config = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组

        $this->result($config,200);
    }


}
